<template>
  <el-dialog v-model="localVisible" title="新增用户" width="30%" center @close="handleCancel">
    <el-form :model="InsertForm" :rules="InsertRules" ref="InsertFormRef" label-position="top" label-width="0px">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="InsertForm.name"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="InsertForm.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="InsertForm.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="用户角色" prop="role">
        <el-select v-model="InsertForm.role" placeholder="请选择用户角色">
          <el-option label="普通用户" value="普通用户"></el-option>
          <el-option label="会员" value="会员"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span class="dialog-footer">
      <el-button type="primary" @click="onInsert">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import axios from 'axios';
import { defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus'

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})

const props = defineProps({
  visible: Boolean,
});

const emit = defineEmits(['update:visible', 'add']);

const localVisible = ref(props.visible);

watch(() => props.visible, (newValue) => {
  localVisible.value = newValue;
});

watch(localVisible, (newValue) => {
  if (!newValue) {
    emit('update:visible', false);
  }
});

const InsertForm = ref({
  name: '',
  email: '',
  phone: '',
  role: ''
});

const InsertRules = {
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  role: [
    { required: true, message: '请输入角色信息', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!['普通用户', '会员'].includes(value)) {
          callback(new Error('角色必须为普通用户或会员'));
        } else {
          callback();
        }
      }, 
      trigger: 'change'
    }
  ]
};

const InsertFormRef = ref(null);

const onInsert = () => {
  InsertFormRef.value.validate((valid) => {
    if (valid) {
      api.post('/api/v1/user/user-info', InsertForm.value
        ).then(response => {
          if (response.data.code == "200"){
            ElMessage({
              title: '成功',
              message: '新增成功',
              type: 'success',
              showClose: false,
            });
            localVisible.value = false;
            emit('add');
          } else {
            ElMessage({
              title: '错误',
              message: '新增失败！' + response.data.message,
              type: 'error',
          });
          }
        }).catch(error => {
          ElMessage({
            title: '错误',
            message: '新增失败！' + error.message,
            type: 'error',
          });
        });
    } else {
      return false;
    }
  });
};

const handleCancel = () => {
  localVisible.value = false;
  resetInsertForm();
};
const resetInsertForm = () => {
  InsertForm.value = {
    name: '',
    email: '',
    phone: '',
    role: ''
  }
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: space-evenly; 
  margin-top: 20px; 
}

.dialog-footer .el-button {
  width: 30%;
  height: 45px;
  font-size: 16px;
  margin-top: 20px; 
}
.el-select {
  width: 180px;
}
</style>